package com.ruoyi.user.utils;

import com.ruoyi.user.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author Lu.F
 * @version 1.0
 * @date 2022/11/10 16:03
 */
@Slf4j
public class JwtUtil {

    private static final String SECRET = "org.oop";

    private static final String TOKEN_PREFIX = "oopGroup";

    private static final String SUBJECT = "yxc_app";

    /**
     * 设置token期限为一周
     */
    private static final long EXPIRATION = 7*24*60*60*1000;

    /**
     * 生成token
     * @param loginUser
     * @return
     */
    public static String geneToken(LoginUser loginUser){

        if (loginUser == null){
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .claim("uname", loginUser.getUname())
                .claim("id", loginUser.getId())
                .claim("utell", loginUser.getUtell())
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        return TOKEN_PREFIX+token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        }catch (Exception e){
            log.warn("token 错误",e);
            return null;
        }
    }
}
